package com.webapp.org.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.webapp.org.bean.CategoryBean;
import com.webapp.org.interfaces.ICategory;
import com.webapp.org.util.condatabase.HBConfigure;

public class CategoryDAO implements ICategory
{
	private SessionFactory sf = HBConfigure.getSessionFactory();
	private boolean result = false;

	/* Method to insert an category from the records */
	public boolean insertCategory(CategoryBean categoryBean)
	{
		result = false;
		Session session = sf.openSession();
		session.beginTransaction();
		try
		{
			session.persist(categoryBean);
			session.getTransaction().commit();
			result = true;
		} catch (Exception exception)
		{
			session.getTransaction().rollback();
			System.out.println("Error occured while inserting");
		} finally
		{
			session.close();
		}
		return result;
	}

	/* Method to update an category from the records */
	public boolean updateCategory(CategoryBean categoryBean)
	{
		result = false;
		Session session = sf.openSession();
		session.beginTransaction();
		try
		{
			session.update(categoryBean);
			session.getTransaction().commit();
			result = true;
		} catch (Exception e)
		{
			session.getTransaction().rollback();
			System.out.println("Exception took pplace in update");
		} finally
		{
			session.close();
		}
		return result;
	}

	/* Method to DELETE an category from the records */
	public boolean deleteCategory(int categoryId)
	{
		result = false;
		Session session = sf.openSession();
		session.beginTransaction();
		try
		{

			CategoryBean categoryBean = (CategoryBean) session.get(
					CategoryBean.class, categoryId);
			session.delete(categoryBean);
			session.getTransaction().commit();
			result = true;
		} catch (Exception e)
		{
			session.getTransaction().rollback();
			System.out.println("error while deleting");
		} finally
		{
			session.close();
		}
		return result;
	}

	/* Method to retrieve an category from the records */
	public List<CategoryBean> retrieveCategory()
	{
		List<CategoryBean> categoryList = null;
		Session session = sf.openSession();
		session.beginTransaction();
		try
		{
			categoryList = session.createQuery("FROM CategoryBean").list();
			session.getTransaction().commit();
			result = true;
		} catch (Exception e)
		{
			session.getTransaction().rollback();
			System.out.println("Error while retriving category data");
		} finally
		{
			session.close();
		}
		return categoryList;
	}

}
